<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>{{ $t('route.businessCategor') }}</h2>
        </template>
        <template v-slot:after>
          <el-button class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-edit" :disabled="!checkPermission('businessCategor-add')" @click="addOrEidt('add',0)">{{ $t('button.add') }}</el-button>
        </template>
      </PageTitle>
      <!-- 数据表 -->
      <el-table v-loading="downloadLoading" border :data="list" max-height="650px" style="margin-top: 20px;">
        <el-table-column label="ID" prop="id" sortable="custom" width="60" />
        <el-table-column :label="$t('table.CateName')" prop="name" />
        <el-table-column :label="$t('table.CatePic')" prop="pic">
          <template slot-scope="{row}">
            <div class="table-img">
              <img :src="row.pic" width="100%">
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.state')" prop="status">
          <template slot-scope="{row}">
            <el-tag :type="row.status|statusFilter">
              {{ row.status|formStatusData }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.creationTime')" prop="created_at">
          <template slot-scope="{row}">
            {{ row.createtime|timeStanp }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" width="380" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button icon="el-icon-edit" type="primary" size="mini" :disabled="!checkPermission('businessCategor-edit')" @click="addOrEidt('edit',row)">{{ $t('button.edit') }}</el-button>
            <el-button type="success" icon="el-icon-warning-outline" size="mini" :disabled="!checkPermission('businessCategor-set')" @click="openRole(row)">{{ $t('button.Binding') }}</el-button>
            <el-button icon="el-icon-delete" type="dang er" size="mini" :disabled="!checkPermission('businessCategor-del')" @click="delData(row.id)">{{ $t('button.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" align="middle" style="margin-top:20px">
        <el-pagination background layout="total,prev,pager,next" :total="count" :page-size="query.limit" :current-page="query.page" @current-change="changPage" />
      </el-row>
    </div>
    <!-- 添加 -->
    <el-dialog :title="dialogTitle" :visible="showDialog" @opened="openDialog" @close="btnCanle">
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="150px">
        <el-form-item :label="$t('table.CateName')">
          <el-input v-model="formData.name" :placeholder="$t('table.enterThe')+' '+$t('table.CateName')" style="width:50%" />
        </el-form-item>
        <el-form-item :label="$t('table.CatePic')">
          <ImageUpload ref="staffPhoto" />
        </el-form-item>
        <el-form-item :label="$t('table.state')">
          <el-select v-model.number="formData.status" :placeholder="$t('table.selectThe')+' '+$t('table.state')">
            <el-option v-for="(item,index) in statusData" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanle">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnOk">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!-- 绑定分类 -->
    <el-dialog :visible="roleShowDialog" :title="$t('button.Configurepermissions')" @close="btnCanleRole">
      <el-tree ref="permTree" :data="permData" :props="defaultProps" :show-checkbox="true" :default-checked-keys="selectCheck" node-key="id" :check-strictly="true" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanleRole">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnPermOK">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getBusinessCate, addBusinessCate, delBusinessCate, getShopCateList, ShopCateBinding } from '@/api/user'
import { tranListTotreeDatapid } from '@/utils'
import user from '@/store/modules/user'
export default ({
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      downloadLoading: false,
      statusData: [{
        id: 1,
        value: this.$t('table.normal')
      },
      {
        id: 2,
        value: this.$t('table.deactivate')
      }],
      query: {
        aid: 1,
        bid: undefined,
        page: 1,
        limit: 10
      },
      count: 0,
      dialogTitle: this.$t('table.addbusinessCate'),
      formData: {
        aid: 1,
        id: undefined,
        name: '',
        pic: '',
        status: undefined,
        sort: 0
      },
      rules: {
        name: [{ required: true, message: this.$t('table.name') + this.$t('prompt.noEmpty'), trigger: 'blur' }],
        status: [{ required: true, message: this.$t('table.state') + this.$t('prompt.noEmpty'), trigger: 'blur' }]
      },
      showDialog: false,
      roleShowDialog: false,
      permData: [],
      defaultProps: {
        label: 'name'
      },
      selectCheck: [], // 定义一个数组来接收 已经选中的节点
      roleId: undefined// 用来记录分配角色的id
    }
  },
  created() {
    // 获取userid
    this.getBusinessCateList()
    this.query.bid = parseFloat(user.state.userInfo.bid)
  },
  methods: {
    // 获取商户分了列表
    async getBusinessCateList() {
      this.downloadLoading = true
      const { count, list } = await getBusinessCate(this.query)
      this.list = list
      this.count = count
      this.downloadLoading = false
    },
    // 点击展开新增修改
    addOrEidt(type, row) {
      if (type === 'add') {
        this.dialogTitle = this.$t('table.addbusinessCate')
        this.formData.id = undefined
        this.formData.name = ''
        this.formData.pic = ''
        this.formData.status = undefined
        this.formData.sort = 0
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      } else if (type === 'edit') {
        this.dialogTitle = this.$t('table.editbusinessCate')
        this.formData.id = row.id
        this.formData.name = row.name
        this.formData.status = row.status
        this.formData.pic = row.pic
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },
    // 点击确定时
    async btnOk() {
      try {
        // 校验整个表单
        await this.$refs.ruleForm.validate()
        // 读取上传组件的数据
        const fileList = this.$refs.staffPhoto.fileList
        // 循环判断是否已经完成全部上传
        if (fileList.some(item => !item.upload)) {
          //  如果此时去找 upload为false的图片 找到了说明 有图片还没有上传完成
          this.$message.warning(this.$t('prompt.noImage'))
          return
        }
        this.formData = { ...this.formData, pic: fileList && fileList.length ? fileList[0].url : '' }
        // 调用新增接口
        await addBusinessCate(this.formData)
        // 更新数据
        this.getBusinessCateList()
        this.btnCanle()
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 删除管理员
    async delData(e) {
      const data = {
        id: e
      }
      try {
        await this.$confirm(this.$t('prompt.deleteit'))
        await delBusinessCate(data)
        this.getBusinessCateList()
        this.$message.success(this.$t('prompt.deletesuccess'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 给图片赋值
    openDialog() {
      if (this.formData.pic) {
        this.$refs.staffPhoto.fileList = [{ url: this.formData.pic, upload: true }]
      }
    },
    // 取消重置原来的数据
    btnCanle() {
      this.formData = {
        id: undefined,
        name: '',
        pic: '',
        status: undefined,
        sort: 0
      }
      this.$refs.staffPhoto.fileList = []
      this.$refs.ruleForm.clearValidate()// 重置校验结果
      this.showDialog = false
    },
    // 分页
    changPage(newPage) {
      this.query.page = newPage
      this.getBusinessCateList()
    },
    // 取消权限配置
    btnCanleRole() {
      this.roleId = undefined
      this.selectCheck = null
      this.roleShowDialog = false
    },
    // 打开权限
    async openRole(row) {
      await this.getMenu()
      this.roleId = row.id
      this.selectCheck = row.cate_id.split(',')
      this.roleShowDialog = true
    },
    // // 获取权限菜单
    async getMenu() {
      const { list } = await getShopCateList(this.query)
      this.permData = list
      // 调用自定义的树状数组函数，处理获取的数组
      if (this.permData != null) {
        this.permData = tranListTotreeDatapid(this.permData, 0)
      }
    },
    // 确定配置权限
    async btnPermOK() {
      // 调用el-tree的方法
      console.log(this.$refs.permTree.getCheckedKeys().toString())

      const data = {
        id: this.roleId,
        cate_id: this.$refs.permTree.getCheckedKeys().toString()
      }
      try {
        await ShopCateBinding(data)
        this.getBusinessCateList()
        this.roleShowDialog = false
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        this.$message.error(this.$t('prompt.failed'))
      }
    }
  }
})
</script>
<style lang="scss">
.table-img{
  width: 90px;
}
</style>
